package com.ml.rocketmq.base.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * 发送同步消息
 */
public class SyncProducer {

	public static void main(String[] args) throws Exception {
    	// 创建一个producer，参数为Producer Group名称
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
    	// 设置NameServer的地址
    	producer.setNamesrvAddr("localhost:9876");
		// 设置当发送失败时重试发送的次数，默认为2次
		producer.setRetryTimesWhenSendFailed(3);
		// 设置发送超时时限为5s，默认3s
		producer.setSendMsgTimeout(5000);
    	// 启动Producer
        producer.start();

    	for (int i = 0; i < 100; i++) {
    	    // 创建消息，并指定Topic，Tag和消息体
			byte[] messageBody = ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET);
			Message msg = new Message("TopicTest","TagA", messageBody);
			// 为消息指定key
			msg.setKeys("key-" + i);
        	// 同步发送消息
            SendResult sendResult = producer.send(msg);
            // 通过sendResult返回消息是否成功送达
            System.out.printf("%s%n", sendResult);
    	}
    	// 如果不再发送消息，关闭Producer
    	producer.shutdown();
    }
}